/// <reference path="../../../../../../../typings/angularjs/angular.d.ts" />

define(['./../../initial', './../../model/Project', './../../model/StatisticInputItem', './../../service/chartFactory'],
    function () {
        var app = angular.module('App.home');

        app.controller('statistic.lineLongCtrl', ['$scope', '$timeout', '$rootScope', '$state', '$stateParams', 'allProjects', 'StatisticInputItem', 'curLine', 'chartFactory', 'statisticInputItemList', '$q',
            function ($scope, $timeout, $rootScope, $state, $stateParams, allProjects, StatisticInputItem, curLine, chartFactory, statisticInputItemList, $q) {
				
                //初始化3种类型
                $scope.minItem = new StatisticInputItem('less');
                $scope.betweenItem = new StatisticInputItem('between');
                $scope.maxItem = new StatisticInputItem('more');
                //当前radio选择的类型
                $scope.type = "between";
                //当前的项目类型,目前为长期沉降或重点段
                $scope.projectTypeCode = $stateParams.projectTypeCode;
                $scope.setType = function (type) {
                    $scope.type = type;
                };

                $scope.conditionTitle = "查询条件:";
                $scope.conditions = statisticInputItemList.conditions;
                $scope.searchType = 'design'; //默认是设计值查询 
                $scope.clickType = 'design'; //默认是设计值查询 
                //侦听查询类型改变
                $scope.$watch('clickType', function (newV, oldV) {
                    // if (newV === oldV) return;
                    statisticInputItemList.searchType = newV;
                    statisticInputItemList.changeUnit();
                });
                $scope.addCondition = function () {
                    $('#addCondition').popup('hide');
                    switch ($scope.type) {
                        case 'less':
                            statisticInputItemList.addCondition('less', 0, $scope.minItem.max);
                            break;
                        case 'between':
                            statisticInputItemList.addCondition('between', $scope.betweenItem.min, $scope.betweenItem.max);
                            break;
                        case 'more':
                            statisticInputItemList.addCondition('more', $scope.maxItem.min);
                            break;
                        default:
                            break;
                    }
                };
                $scope.removeCondition = function (index) {
                    statisticInputItemList.removeCondition(index);
                };

                //初始化radioButtons,使用semantic插件,让样式更美观
                //初始化tab
                //初始化第一次查询
                $timeout(function () {
                    $('.ui.radio.checkbox.checked').checkbox();
                    $('.ui.toggle.checkbox').checkbox();
                    $('#addCondition').popup({
                        on: 'click'
                    });
                    $('.ui.button.icon.right.floated.help').popup({
                        position: 'bottom left'
                    });
                    $('a.item.tab-item').tab();
                    $scope.showTab = false;
                    $scope.chartHeight = document.documentElement.clientHeight - 650;
                    $scope.query();
                }, 800);
                
                //当用户离开的时候
                $scope.$on("$destroy", function () {
                    $scope.stop = true;
                });


                
                //返回一个空的promise对象
                function emptyQ() {
                    return $timeout(function () {

                    }, 0);
                }



                //更新chartData数据
                function generateChartData(chartData, resultData) {
                    resultData.forEach(function (item) {
                        item.datas.forEach(function (data, index) {
                            chartData.datas[index] = {
                                count: chartData.datas[index] ? chartData.datas[index].count + data.count : 0 + data.count,
                                text: data.text,
                                ratio: ''
                            };
                        });
                        chartData.count += item.count;
                    });
                    return chartData;
                }
                
                //统计比例
                function generateChartRatio(chartData) {
                    var sum = chartData.count;
                    chartData.datas.forEach(function (item) {
                        item.ratio = (100 * item.count / sum).toFixed(2) + '%';
                    });
                    return chartData;
                }
                
                
                
                //记录各个location下的时间列表
                $scope.allTimes = [];
                $scope.allTimeListLoaded = false;
                var allTimeList = [], startTimeList = [], endTimeList = [];
                var totalLocationList = [];
                //根据查找到底属于totalLocationList的index
                function findLocationIndex(location) {
                    //为出入场线设置特例
                    if (location.indexOf('出场线') > -1) {
                        return 0;
                    } else if (location.indexOf('入场线') > -1) {
                        return 1;
                    } else {
                        for (var i = 0; i < totalLocationList.length; i++) {
                            if (location.indexOf(totalLocationList[i]) > -1) {
                                return i;
                            }
                        }
                        return -1;
                    }
                }
                //填充所有时间列表
                function filterDataTimesAndLocations(resultData) {
                    if (resultData.length === 0 || $scope.allTimeListLoaded === true) return;
                    //记录所有location的时间列表
                    resultData.forEach(function (item) {
                        //筛选时间
                        item.allTimes && item.allTimes.forEach(function (timeStr) {
                            if (!timeStr) return;
                            var t = new Date(timeStr).getFullYear();
                            if (allTimeList.indexOf(t) < 0) {
                                //防止所有区间测量时间不一致
                                if (allTimeList.length > 0 && t > allTimeList[0]) return;
                                allTimeList.push(t);
                                startTimeList.push(t + "-1-1");
                                endTimeList.push(t + "-12-31");
                            }
                        });
                        //筛选location
                        if (totalLocationList.indexOf(item.location) < 0) {
                            totalLocationList.push(item.location);
                        }
                    });

                }
                
                //每一个项目查询完成后开始更新图表,只在chart为column的时候才可用,此时无法切换到piechart
                function updateChart(chartData) {
                    var chart = $('#chart').highcharts();
                    var data = [];
                    var series = chart.series[0];
                    data = chartData.datas.map(function (item) {
                        return item.count;
                    });
                    series.setData(data);
                }
                
                //统计所有的区间下各location的点数合
                function statisticTotalPointChart() {
                    //为大圆,入场线,出场线设置特例
                    totalLocationList = totalLocationList.filter(function (item) {
                        return item.indexOf('出场线') < 0 && item.indexOf('入场线') < 0;
                    });
                    var series = totalLocationList.map(function (location) {
                        return {
                            name: location,
                            data: []
                        };
                    });
                    var categories = [];
                    curLine.projects.forEach(function (prj, prjIndex) {
                        //先都设置为0
                        series.forEach(function (serie) {
                            serie.data[prjIndex] = 0;
                        });
                        
                        //添加categories
                        categories.push(prj.name);

                        //处理包含的location
                        prj.tempConvergenceList.forEach(function (convergenceData) {
                            var tempIndex = findLocationIndex(convergenceData.location);
                            if (tempIndex > -1) {
                                series[tempIndex].data[prjIndex] += convergenceData.count;
                            }
                        });

                    });

                    var chartData = {
                        title: curLine.name + '各区间环数统计',
                        categories: categories,
                        series: series
                    };
                    chartFactory.createTotalPointBar("#totalChart", chartData, document.getElementById('conditionContainer').clientWidth - 60, document.documentElement.clientHeight - 300);
                }

                $scope.busy = true;
                //查询函数,开始查询一条线路的最近变化数据,searchType为查询的类型,分为design和diff
                $scope.query = function (timeIndex, searchType, $event) {
                    if ($scope.budy) return;//如果还在查询,不予执行
                    if (searchType === 'diff') {
                        var count = $scope.allTimes.filter(function (item) {
                            return item.checked;
                        }).length;
                        if (count < 2) {
                            //暂时不发送事件,让用户继续点击下一个时间
                            $event && $event.stopPropagation();
                            return;
                        }
                    }
                    //一旦开始查询,自动选择到图表tab页
                    $('a.item.tab-item').tab('change tab', 'tab0');
                    //构建初始的chartData
                    var chartData = {
                        title: curLine.name + '设计值统计查询',
                        datas: [],
                        count: 0
                    };
                    //处理起始,结束时间
                    var startTime = undefined, endTime = undefined;
                    if (typeof (timeIndex) !== 'undefined') {
                        if (searchType === 'design') {
                            startTime = startTimeList[timeIndex];
                            endTime = endTimeList[timeIndex];
                            $scope.startYear = $scope.allTimes[timeIndex].time;
                            chartData.title = curLine.name + $scope.startYear + "收敛设计值统计查询";
                        } else if (searchType === 'diff') {
                            var selectedTimeIndex = $scope.allTimes.map(function (item, index) {
                                if (item.checked) {
                                    return index;
                                } else {
                                    return -1;
                                }
                            }).filter(function (item) {
                                return item > -1;
                            });
                            startTime = startTimeList[selectedTimeIndex[1]];
                            endTime = endTimeList[selectedTimeIndex[0]];
                            $scope.startYear = $scope.allTimes[selectedTimeIndex[1]].time;
                            $scope.endYear = $scope.allTimes[selectedTimeIndex[0]].time;
                            chartData.title = curLine.name + $scope.startYear + '至' + $scope.endYear + "收敛阶段统计查询";
                            //取消所有时间的checked设置
                            $scope.allTimes.forEach(function (item) {
                                item.checked = false;
                            });
                        }
                    }
                    //赋值查询类型
                    $scope.searchType = searchType || 'design';
                    $scope.busy = true;
                    $scope.resultList = [];
                    var chart = null;
                    var createChart = true; // 是否可以开始建立chart,如果数据是空的就不建立
                    //依次逐步查询每个项目的收敛统计数据
                    curLine.projects.reduce(function (pre, prj, index) {
                        if (!$scope.stop) {
                            return pre.then(function (data) {
                                var defer = $q.defer();
                                prj.getLocationList('收敛')
                                    .then(function (locationStrList) {
                                        //获取LocationList
                                        return prj.postConvergence({
                                            locationList: locationStrList,
                                            conditions: $scope.conditions,
                                            startTime: startTime,
                                            endTime: endTime,
                                            fuzzy: typeof (timeIndex) !== 'undefined' ? '1' : '0',
                                            isDesign: true,
                                            searchType: $scope.searchType
                                        });
                                    }).then(function (resultData) {
                                        if (resultData.length === 0) {
                                            if (index === curLine.projects.length - 1) {
                                                lastProject();
                                            }
                                            defer.resolve();
                                            return;
                                        }
                                        //获取最终的结果
                                        var resultItem = {
                                            name: prj.name,
                                            resultData: resultData
                                        };

                                        $scope.resultList.push(resultItem);
                                        //筛选时间,单位为年,筛选所有的location
                                        filterDataTimesAndLocations(resultData);
                                        //生成图表可用的数据
                                        $scope.chartData = chartData = generateChartData(chartData, resultData);
                                        //通过index判断当前的进度状态
                                        if (createChart) {
                                            $scope.showTab = true;
                                            //绘制图表
                                            chartFactory.createStastisBar("#chart", chartData, document.getElementById('conditionContainer').clientWidth - 60, document.documentElement.clientHeight - 300);
                                            //赋值chart
                                            chart = $('#chart').highcharts();
                                            chart.notFinish = true;
                                            createChart = false;
                                        } else {
                                            //更新图表的数据
                                            updateChart(chartData);
                                        }
                                        //最后一个完成了
                                        if (index === curLine.projects.length - 1) {
                                            lastProject();
                                        }
                                        defer.resolve(resultData);
                                    });
                                return defer.promise;
                            });
                        } else {
                            //用户leave的时候,如果查询还在进行,返回空promise
                            //防止网络消耗
                            return emptyQ;
                        }
                    }, emptyQ());
                };
                
                //处理最后一个项目
                function lastProject() {
                    generateChartRatio($scope.chartData);
                    //时间列表加载完,只需要一次,以后不用了
                    if ($scope.allTimeListLoaded === false) {
                        $scope.allTimes = allTimeList.map(function (tt, i) {
                            return {
                                time: tt.toString() + '年',
                                active: i === 0
                            };
                        });
                        $scope.startYear = $scope.allTimes[0].time;
                        $scope.allTimeListLoaded = true;
                        //绘制点数统计图
                        statisticTotalPointChart();
                        $timeout(function () {
                            $('#queryBtn').dropdown();
                            $('#queryDiffBtn').dropdown({
                                action: 'hide'
                            });
                        }, 500);
                    }
                    //设置为不busy,chart可切换成pie
                    var chart = $('#chart').highcharts();
                    chart.notFinish = $scope.busy = false;
                }
            }]);
    });